`include "mycpu.h"
module if_stage(
    input clk,
    input reset,
    //ID allowin
    input ds_allowin,
    //32: branch valid 31-0: branch target
    input [`BR_BUS_WD - 1:0] br_bus,
    //IF stage to ID stage
    output fs_to_ds_valid,
    output [`FS_TO_DS_WD - 1:0] fs_to_ds_bus,
    //inst_sram
    output inst_sram_en,
    output [3:0] inst_sram_wen,
    output [31:0] inst_sram_addr,
    input [31:0] inst_sram_rdata,
    output [31:0] inst_sram_wdata
);
    //fs valid bit
    reg fs_valid;
    wire fs_allowin;
    wire fs_ready_go;
    wire to_fs_valid;
    //pc
    reg [31:0] fs_pc;
    wire [31:0] nextpc;
    wire [31:0] seq_pc;
    wire [31:0] fs_inst;

    assign fs_to_ds_bus[`FS_TO_DS_WD - 1:0] = {
        fs_inst[31:0],
        fs_pc[31:0]
    };

    //pre-IF
    assign nextpc[31:0] = br_bus[32]? br_bus[31:0] : seq_pc;
    assign seq_pc = fs_pc + 32'h4;

    //IF stage
    assign to_fs_valid  = ~reset;
    assign fs_ready_go = 1'b1;
    assign fs_allowin = !fs_valid || fs_ready_go && ds_allowin;
    assign fs_to_ds_valid = fs_valid;

    assign inst_sram_en = fs_allowin && to_fs_valid;
    assign inst_sram_wen = 4'b0;
    assign inst_sram_addr = nextpc;
    assign inst_sram_wdata = 32'b0;
    assign fs_inst = inst_sram_rdata;


    always @(posedge clk) begin
        if(reset) begin
            fs_pc <= 32'h1bfffffc;
        end
        else if(ds_allowin)begin
            fs_pc <= nextpc;
        end
    end
    always @(posedge clk) begin
        if(reset) begin
            fs_valid <= 1'b0;
        end
        else if(to_fs_valid && fs_allowin)begin
            fs_valid <= to_fs_valid;
        end
    end

endmodule